﻿/*****************************************************************
// Copyright (C) 2011-2099 ZdSoft Corporation
// All rights reserved.
// 
// Author:       wunaigong
// Create Date:  2011-07-20 22:15:47
// Usage: Rsa加密解密类
//
// RevisionHistory
// Date				Author				Description
*****************************************************************/

using System;
using System.Security.Cryptography;
using System.Text;

namespace Portal
{
    [Serializable]
    public class Rsa
    {
        //私钥
        private readonly string _privateKey = AppGlobals.ReadXml(AppGlobals.GetAppPath() + @"\PrivateKey.xml").InnerXml;
        private readonly string _publicKey = AppGlobals.ReadXml(AppGlobals.GetAppPath() + @"\PublicKey.xml").InnerXml;
        //实例化Rsa操作类
        private readonly RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider();

        /// <summary>
        /// 获取RsaKeys
        /// </summary>
        /// <returns></returns>
        public RsaKeys GetRsaKeys()
        {
            return (RsaKeys)XmlUtils.Deserialize(typeof(RsaKeys), AppGlobals.GetAppPath() + @"\RsaKeys.xml") ?? new RsaKeys();
        }


        /// <summary>
        /// 公钥
        /// </summary>
        public string PublicKey
        {
            get
            {
                return _publicKey;
            }
        }

        /// <summary>
        /// 私钥
        /// </summary>
        public string PrivateKey
        {
            get
            {
                return _privateKey;
            }
        }

        /// <summary>
        /// 生成私钥
        /// </summary>
        /// <returns>私钥</returns>
        public string GetPrivateKey()
        {

            return _rsa.ToXmlString(true);
        }

        /// <summary>
        /// 生成公钥
        /// </summary>
        /// <returns>公钥</returns>
        public string GetPublicKey()
        {
            return _rsa.ToXmlString(false);
        }

        /// <summary>
        /// 生成许可证（这个应该）
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="registerKey"></param>
        /// <returns></returns>
        public string PrepareLicenceKey(string privateKey, string registerKey)
        {
            this._rsa.FromXmlString(privateKey);
            var f = new RSAPKCS1SignatureFormatter(this._rsa);
            f.SetHashAlgorithm("SHA1");
            byte[] source = Encoding.ASCII.GetBytes(registerKey);
            byte[] result = new SHA1Managed().ComputeHash(source);
            return Convert.ToBase64String(f.CreateSignature(result));
        }

        /// <summary>
        /// 生成许可证（这个应该）
        /// </summary>
        /// <param name="registerKey"></param>
        /// <returns></returns>
        public string PrepareLicenceKey(string registerKey)
        {
            this._rsa.FromXmlString(PrivateKey);
            var f = new RSAPKCS1SignatureFormatter(this._rsa);
            f.SetHashAlgorithm("SHA1");
            byte[] source = Encoding.ASCII.GetBytes(registerKey);
            byte[] result = new SHA1Managed().ComputeHash(source);
            return Convert.ToBase64String(f.CreateSignature(result));
        }

        /// <summary>
        /// 验证许可
        /// </summary>
        /// <param name="licenceKey">许可证编码</param>
        /// <param name="registerKey">注册码(机器码)</param>
        /// <returns></returns>
        public bool CheckLicneceKey(string licenceKey, string registerKey)
        {
            try
            {
                _rsa.FromXmlString(PublicKey);
                var f = new RSAPKCS1SignatureDeformatter(_rsa);
                f.SetHashAlgorithm("SHA1");
                var key = Convert.FromBase64String(licenceKey);
                var name = new SHA1Managed().ComputeHash(Encoding.ASCII.GetBytes(registerKey));
                return f.VerifySignature(name, key);
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// SHA加密
        /// </summary>
        /// <param name="source">源文</param>
        /// <returns>密文</returns>
        public string EncBySha1(string source)
        {
            new RSAPKCS1SignatureDeformatter(_rsa).SetHashAlgorithm("SHA1");
            try
            {
                var sha = new SHA1Managed();
                return Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(source)));
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }





        /// <summary>
        /// 生成注册码(机器码)
        /// </summary>
        /// <param name="softName">软件名称</param>
        /// <returns>注册码(机器码)</returns>
        public string PrepareRegisterKey(string softName)
        {
            var f = new RSAPKCS1SignatureFormatter(this._rsa);
            string rk = softName + "-" +new HardwareInfo().GetCpuID();
            f.SetHashAlgorithm("SHA1");
            return this.EncBySha1(rk);
        }

        //public string ShowRegisterForm(string chn, string eng)
        //{
        //    var f = new frmRegister();
        //    f.SoftNameChn = chn;
        //    f.SoftNameEng = eng;
        //    f.Show();
        //    f.Activate();
        //    return "";
        //}

        //public string PrivateKey
        //{
        //    get
        //    {
        //        return this._privateKey;
        //    }
        //}


    }
}